package com.macro.mall.controller;

import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.TiTrainingUser;
import com.macro.mall.model.UmsCommunity;
import com.macro.mall.model.UmsMember;
import com.macro.mall.service.TiTrainingUserService;
import com.macro.mall.service.UmsCommunityService;
import com.macro.mall.service.UmsMemberService;
import com.macro.mall.utils.Mapping;
import com.macro.mall.utils.ProvinceUtil;
import com.macro.mall.utils.ReadExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TiTrainingUser的路由接口服务
 *
 * @author
 */
@Slf4j
@RestController
@RequestMapping("TiTrainingUserController")
@Api(tags = "专题用户信息表", description = "专题用户信息表")
public class TiTrainingUserController {
    private static final String KEY = "USER_TITRAINING_IMPORT";

    /**
     * TiTrainingUserService服务
     */
    @Autowired
    private TiTrainingUserService tiTrainingUserService;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private UmsCommunityService umsCommunityService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ReadExcelUtil readExcelUtil;
    @Autowired
    private ProvinceUtil provinceUtil;

    /**
     * 查询所有数据的方法
     *
     * @param
     * @return
     */
    @GetMapping(value = "/list", produces = {"application/json;charset=UTF-8"})
    public CommonResult find(@RequestParam(value = "username",required = false) String username,
                             @RequestParam(value = "phone",required = false) String phone,
                             @RequestParam(value = "communityName",required = false) String communityName,
                             @RequestParam(value = "userIdentityName",required = false) String userIdentityName,
                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                             @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        return CommonResult.success(CommonPage.restPage(tiTrainingUserService.find(username,phone,communityName,userIdentityName,pageNum,pageSize)));
    }

    /**
     * 导入用户
     *
     * @param
     * @return
     */
//    @ResponseBody
//    @ApiOperation("导入用户")
//    @PostMapping(value = "/importUser", produces = {"application/json;charset=UTF-8"})
    public CommonResult importUser() {
        tiTrainingUserService.importUserNotNull();
        return CommonResult.success(null);
    }



//    @ApiOperation(value = "导入-用户信息导入", notes = "导入-用户信息导入接口")
//    @PostMapping(value = "/userImportTiTraining")
    public CommonResult boothUpload(@ApiParam(value = "文件") @RequestParam("file") MultipartFile file) throws IOException {
        Map<String, Object> map = new HashMap<>();
        try {
            ValueOperations objOps = redisTemplate.opsForValue();
            boolean bSet = objOps.setIfAbsent(KEY, "processing");
            if (!bSet) {
                String message = "processor is running, cannot start again.";
                log.error(message + " the key is redis is :" + KEY);
                return CommonResult.failed("请稍后,等待上次文件处理完成后再次尝试.");
            }
            InputStream inputStream = file.getInputStream();
            Workbook wb = ReadExcelUtil.chooseWorkbook("file.xlsx", inputStream);
            TiTrainingUser vo = new TiTrainingUser();
            Map<String, Object> stringObjectMap = readExcelUtil.readTrainingDataListT(wb, vo, 1, 2, 0, map);
            String result = (String) stringObjectMap.get("result");
            String message = (String) stringObjectMap.get("message");
            if (!result.equals("0000")) {
                return CommonResult.failed(message);
            }
            List<TiTrainingUser> data = (List<TiTrainingUser>) stringObjectMap.get("data");
            log.info("boothUploadVOS size : {}", data.size());
            for (TiTrainingUser one : data) {
                UmsCommunity one1 = umsCommunityService.findOne(Long.parseLong(one.getCommunityId()+""));
                one.setCommunityId(one1.getId().toString());
                one.setCommunityName(one1.getCommunityName());
                one.setUsername(one.getPhone());
                List<UmsMember> umsMembers = memberService.selectAllByUmsMember(one.getPhone(), null, null, 1, 1);
                if(umsMembers.size() == 0) {
                    UmsMember build = UmsMember.builder().build();
                    BeanUtils.copyProperties(one, build);
                    build.setCommunityId(one1.getId().intValue());
                    build.setCommunityName(one1.getCommunityName());
                    build.setUsername(one.getPhone());
                    memberService.saveUmsMemberSelective(build);
                }else {
                    UmsMember umsMember = umsMembers.get(0);
                    one.setMemberId(umsMember.getId().intValue());
                    one.setCommunityId(umsMember.getCommunityId().toString());
                    one.setCommunityName(umsMember.getCommunityName());
                    one.setUserIdentity(umsMember.getUserIdentity());
                    one.setUserIdentityName(Mapping.getSplitName(umsMember.getUserIdentity()));
                    one.setUsername(umsMember.getUsername());
                }
                tiTrainingUserService.saveNotNull(one);
            }
            if (data.size() < 1) {
                return CommonResult.failed();
            }
        } catch (Exception e) {
            log.error("上传失败", e);
            return CommonResult.failed();
        } finally {
            Boolean delete = redisTemplate.delete(KEY);
        }
        return CommonResult.success(null);
    }

    /**
     * 用户类别管理接口
     *
     * @param
     * @return
     */
//    @ApiOperation("用户类别管理接口")
//    @PostMapping(value = "/manage", produces = {"application/json;charset=UTF-8"})
    public CommonResult manage(@ApiParam(value = "请求报文") @Valid @RequestBody TiTrainingUser value,
                               @RequestParam(value = "oper", defaultValue = "01-新增|02-删除|03-更新|04-查询") @ApiParam(name="oper" ,example="01-新增|02-删除|03-更新|04-查询",required = true)  String oper) {
        return tiTrainingUserService.manageUserNotNull(value,oper);
    }

}
